import logger from 'winston'

const defaultTemplates = {
  403: '403.html',
  404: '404.html',
  500: '500.html'
}

const defaultOptions = {
  text,
  json,
  html,
  templates: defaultTemplates
}

const catchRouterError = (options) => {
  options = Object.assign({}, defaultOptions, options)

  return (ctx, next) => next().catch((err) => {
    if (!err.status) err.status = err.status || 500
    if (!err.message) err.message = err.message || '服务器错误'
    logger.error(err.stack)

    let type = ctx.accepts('html', 'text', 'json')
    type = type || 'text'
    options[type].call(ctx, err, ctx, options)
  })
}

function text (err, ctx) {
  ctx.body = err.message
}

function json (err, ctx) {
  ctx.body = {
    status: err.status,
    message: err.message
  }
}

function html (err, ctx, options) {
  const template = options.templates[err.status]
  if (template) {
    ctx.render(template, {
      err
    })
  } else {
    logger.warn(`Missing template ${err.status}.html`)
  }
}

module.exports = catchRouterError
